package com.jml.spring.aop事务.TransactionUtils;


import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.interceptor.TransactionAspectSupport;


@Aspect
@Component
public class AopTransaction {

	@Autowired
	private TransactionUtils transactionUtils;

	// 异常通知
	@AfterThrowing("execution(* com.jml.spring.aop事务.service.UserService.add(..))")
	public void afterThrowing() {
		System.out.println("事务 异常通知回滚事务....");
		//获取当前事务
		TransactionStatus transactionStatus = TransactionAspectSupport.currentTransactionStatus();
		//回滚当前事务
		transactionStatus.setRollbackOnly();
	}

	// 环绕通知   在方法前后执行
	@Around("execution(* com.jml.spring.aop事务.service.UserService.add(..))")
	public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
		System.out.println("事务 环绕通知开始事务....");
		TransactionStatus transactionStatus = transactionUtils.begin();
		//如果调用方法抛出异常，就不会执行后面的代码，所以在使用事务的时候对于异常不要try，要throw
		proceedingJoinPoint.proceed();
		System.out.println("事务 环绕通知提交事务....");
		transactionUtils.commit(transactionStatus);
	}
}
